package com.cheetah.start.module.monitor.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.cheetah.start.common.base.result.Result;
import com.cheetah.start.common.base.result.ResultController;
import com.cheetah.start.common.base.result.ResultTable;
import com.cheetah.start.common.query.PageQuery;
import com.cheetah.start.common.utils.MyStrUtil;
import com.cheetah.start.module.monitor.domain.OnLine;
import com.cheetah.start.module.system.domain.SysAdmin;
import com.cheetah.start.module.system.service.SysAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 在线控制器
 *
 * @author Feel
 * @date 2021/08/18
 */
@Api(tags = "在线管理")
@Slf4j
@Validated
@RestController
@RequestMapping("/monitor/online")
public class OnLineController extends ResultController {

    @Autowired
    private SysAdminService sysAdminService;

    /**
     * 列表
     *
     * @param pageQuery 页面查询
     * @return {@link ResultTable}
     */
    @ApiOperation(value = "后台在线用户列表")
    @GetMapping("/list")
    public ResultTable list(PageQuery pageQuery, String keyword) {
        List<String> allTokenValue = StpUtil.searchTokenValue(keyword, -1, 100);
        List<String> tokenValue = StpUtil.searchTokenValue(keyword, pageQuery.getPage() - 1, pageQuery.getLimit());
        List<OnLine> onLines = new ArrayList<>();
        for (String token : tokenValue) {
            String subToken = MyStrUtil.sub(token);
            Object loginIdByToken = StpUtil.getLoginIdByToken(subToken);
            Integer adminId = Convert.toInt(loginIdByToken);
            SysAdmin byId = sysAdminService.getById(adminId);
            OnLine onLine = new OnLine();
            BeanUtil.copyProperties(byId, onLine);
            onLine.setToken(subToken);
            onLines.add(onLine);
        }
        return pageTable(onLines, allTokenValue.size());
    }

    /**
     * 退出
     *
     * @return {@link Result}
     */
    @ApiOperation(value = "退出后台用户")
    @PostMapping("/exit")
    public Result exit(String token) {
        StpUtil.logoutByTokenValue(token);
        return success("退出成功");
    }
}
